package beautiful.butterfly.distributed_service_container.http.mvc.wrapper;

import beautiful.butterfly.distributed_service_container.http.handlers.HttpConst;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultFileRegion;
import io.netty.handler.codec.http.*;

import java.io.*;
import java.nio.channels.FileChannel;


public class OutputStreamWrapper implements Closeable, Flushable
{

    private OutputStream outputStream;
    private File file;
    private ChannelHandlerContext channelHandlerContext;

    public OutputStreamWrapper(OutputStream outputStream, File file, ChannelHandlerContext channelHandlerContext)
    {
        this.outputStream = outputStream;
        this.file = file;
        this.channelHandlerContext = channelHandlerContext;
    }

    public File getFile()
    {
        return file;
    }

    public OutputStream getRaw()
    {
        return outputStream;
    }

    public void write(byte[] b) throws IOException
    {
        outputStream.write(b);
    }

    public void write(int b) throws IOException
    {
        outputStream.write(b);
    }

    public void write(byte[] bytes, int off, int len) throws IOException
    {
        outputStream.write(bytes, off, len);
    }

    @Override
    public void flush() throws IOException
    {
        outputStream.flush();
    }

    @Override
    public void close() throws IOException
    {
        try
        {
            this.flush();
            FileChannel fileChannel = new FileInputStream(this.file).getChannel();
            long size = fileChannel.size();

            HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            httpResponse.headers().set(HttpConst.CONTENT_LENGTH.toString(), size + "");
            httpResponse.headers().set(HttpConst.DATE, "");
            httpResponse.headers().set(HttpConst.SERVER, "$/100");//100为任意值


            // Write the initial line and the setHeader.
            channelHandlerContext.write(httpResponse);
            channelHandlerContext.write(new DefaultFileRegion(fileChannel, 0, size), channelHandlerContext.newProgressivePromise());
            // Write the end marker.
            channelHandlerContext.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        } finally
        {
            if (null != outputStream)
            {
                outputStream.close();
            }
        }
    }

}